import * as THREE from 'three';

/**
 // 使用示例
const converter = new CoordinateConverter(renderer);
const clickWorldPos = converter.screenToWorldOnPlane(
  event.clientX,
  event.clientY,
  camera,
  new THREE.Plane(new THREE.Vector3(0, 1, 0), 0)
); 
*/
export class CoordinateConverter {
  private readonly renderer: THREE.WebGLRenderer;
  
  constructor(renderer: THREE.WebGLRenderer) {
    this.renderer = renderer;
  }

  /**
   * 屏幕坐标转NDC（标准化设备坐标）
   */
  screenToNDC(screenX: number, screenY: number): THREE.Vector2 {
    const rect = this.renderer.domElement.getBoundingClientRect();
    return new THREE.Vector2(
      (screenX - rect.left) / rect.width * 2 - 1,
      -((screenY - rect.top) / rect.height) * 2 + 1
    );
  }

  /**
   * 世界坐标转屏幕坐标
   */
  worldToScreen(
    worldPos: THREE.Vector3,
    camera: THREE.Camera
  ): THREE.Vector2 | null {
    const vector = worldPos.clone().project(camera);
    
    if (vector.z > 1) return null; // 在视锥体后面
    
    const x = (vector.x + 1) / 2 * this.renderer.domElement.width;
    const y = (-(vector.y - 1) / 2) * this.renderer.domElement.height;
    
    return new THREE.Vector2(x, y);
  }

  /**
   * 屏幕坐标转世界坐标（与平面交点）
   */
  screenToWorldOnPlane(
    screenX: number,
    screenY: number,
    camera: THREE.Camera,
    plane: THREE.Plane
  ): THREE.Vector3 | null {
    const ndc = this.screenToNDC(screenX, screenY);
    const raycaster = new THREE.Raycaster();
    raycaster.setFromCamera(ndc, camera);
    
    const intersection = new THREE.Vector3();
    return raycaster.ray.intersectPlane(plane, intersection) 
      ? intersection 
      : null;
  }

  /**
   * 屏幕坐标转世界射线
   */
  screenToWorldRay(
    screenX: number,
    screenY: number,
    camera: THREE.Camera
  ): THREE.Ray {
    const ndc = this.screenToNDC(screenX, screenY);
    const raycaster = new THREE.Raycaster();
    raycaster.setFromCamera(ndc, camera);
    return raycaster.ray;
  }
}

